package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.CartAddUuBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.function.DorisMapFunction;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author sw
 * @CreateTime 2024-11-21
 * 12.6 交易域加购各窗口汇总表
 */
public class DwsTradeCartAddUuWindow extends BaseApp{
    public static void main(String[] args) {
        new DwsTradeCartAddUuWindow().start(10026,4,
                Constant.DWS_TRADE_CART_ADD_UU_WINDOW,
                Constant.TOPIC_DWD_TRADE_CART_ADD);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        //添加水位线
        SingleOutputStreamOperator<JSONObject> watermarksStream = getWatermarksStream(dataStreamSource);
        //分组计算加购数据
        SingleOutputStreamOperator<CartAddUuBean> streamOperator = extracted(watermarksStream);
        //开窗聚合
        SingleOutputStreamOperator<CartAddUuBean> result = getResult(streamOperator);
        result.print();
        //写到doris
        result.map(new DorisMapFunction<>())
                .sinkTo(FlinkSinkUtil.getDorisSink("dws_trade_cart_add_uu_window"));
    }

    private static SingleOutputStreamOperator<CartAddUuBean> getResult(SingleOutputStreamOperator<CartAddUuBean> streamOperator) {
         return streamOperator.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<CartAddUuBean>() {
                            @Override
                            public CartAddUuBean reduce(CartAddUuBean x, CartAddUuBean y) throws Exception {
                                x.setCartAddUuCt(x.getCartAddUuCt() + y.getCartAddUuCt());
                                return x;
                            }
                        },
                        new ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>() {
                            @Override
                            public void process(ProcessAllWindowFunction<CartAddUuBean, CartAddUuBean, TimeWindow>.Context context, Iterable<CartAddUuBean> iterable, Collector<CartAddUuBean> collector) throws Exception {
                                CartAddUuBean cartAddUuBean = iterable.iterator().next();
                                cartAddUuBean.setStt(DateFormatUtil.tsToDateTime(context.window().getStart()));
                                cartAddUuBean.setEdt(DateFormatUtil.tsToDateTime(context.window().getEnd()));
                                cartAddUuBean.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
                                collector.collect(cartAddUuBean);
                            }
                        });
    }

    private static SingleOutputStreamOperator<CartAddUuBean> extracted(SingleOutputStreamOperator<JSONObject> watermarksStream) {
        return watermarksStream.keyBy(x -> x.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, CartAddUuBean>() {
                    ValueState<String> lastCartAddState;

                    @Override
                    public void open(Configuration parameters) {
                        lastCartAddState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("lastCartAddState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, CartAddUuBean>.Context context, Collector<CartAddUuBean> collector) throws Exception {
                        String today = DateFormatUtil.tsToDate(jsonObject.getLong("ts"));
                        String lastCartAddValue = lastCartAddState.value();
                        Long cartAddUuCt = 0L;
                        if (!today.equals(lastCartAddValue)) {
                            cartAddUuCt = 1L;
                            lastCartAddState.update(today);
                        }
                        collector.collect(new CartAddUuBean("", "", "", cartAddUuCt));
                    }
                });
    }

    private static SingleOutputStreamOperator<JSONObject> getWatermarksStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.map(JSON::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner((event, timestamp) -> event.getLong("ts") * 1000)
                        .withIdleness(Duration.ofSeconds(120)));
    }

}
















